package com.awesomeproject.module

import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableMap
import org.json.JSONObject
import org.json.JSONStringer
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

class CryptoModule(reactApplicationContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactApplicationContext) {
    override fun getName(): String {
        return "CryptoModule"
    }

    @ReactMethod(isBlockingSynchronousMethod = true)
    fun md5(text: String?): String? {
        if (text.isNullOrBlank()) return null
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            val mdInst = MessageDigest.getInstance("MD5")
            // 使用指定的字节更新摘要
            mdInst.update(text.toByteArray())
            // 获得密文
            val md = mdInst.digest()
            // 把密文转换成十六进制的字符串形式
            val hexString = StringBuffer()
            // 字节数组转换为 十六进制 数
            for (i in md.indices) {
                val shaHex = Integer.toHexString(md[i].toInt() and 0xFF)
                if (shaHex.length < 2) {
                    hexString.append(0)
                }
                hexString.append(shaHex)
            }
            return hexString.toString().substring(8, 24)
        } catch (e: NoSuchAlgorithmException) {
            Log.e(this.javaClass.simpleName, e.message ?: "")
        }
        return ""
    }

    @ReactMethod(isBlockingSynchronousMethod = true)
    fun sha256(text: String?): String? {
        if (text.isNullOrBlank()) return null
        try {
            val digest = MessageDigest.getInstance("SHA-256")
            digest.update(text.toByteArray())
            val messageDigest = digest.digest()
            // Create Hex String
            val hexString = StringBuffer()
            // 字节数组转换为 十六进制 数
            for (i in messageDigest.indices) {
                val shaHex = Integer.toHexString(messageDigest[i].toInt() and 0xFF)
                if (shaHex.length < 2) {
                    hexString.append(0)
                }
                hexString.append(shaHex)
            }
            return hexString.toString()
        } catch (e: NoSuchAlgorithmException) {
            Log.e(this.javaClass.simpleName, e.message ?: "")
        }
        return ""
    }

    @ReactMethod(isBlockingSynchronousMethod = true)
    fun getNetDefense(token: String?, version: String?): String? {
        val netDefense = NetDefenseUtils.getNetDefense(token, version)
        val result = JSONObject()
        result.put("x-yp-nonce", netDefense.nonce)
        result.put("x-yp-sign", netDefense.sign)
        return result.toString()
    }
}